package com.jiuyin.dianjing.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Layout;
import android.util.AttributeSet;
import android.util.TypedValue;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.util.DisplayUtil;

public class TextFloatingActionButton extends FloatingActionButton {
    private String mText;
    private TextDrawable mTextDrawable;
    private int mTextColor;
    private int mTextSize;
    private int mTextStyle;

    public TextFloatingActionButton(Context context) {
        super(context);
        initView(null);
    }

    public TextFloatingActionButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(attrs);
    }

    public TextFloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(attrs);
    }

    private void initView(AttributeSet attrs) {
        if (attrs == null) return;
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TextFloatingActionButton);
        mText = typedArray.getString(R.styleable.TextFloatingActionButton_android_text);
        mTextColor = typedArray.getColor(R.styleable.TextFloatingActionButton_android_textColor, Color.BLACK);
        mTextSize = typedArray.getDimensionPixelSize(R.styleable.TextFloatingActionButton_android_textSize, DisplayUtil.dp2px(getContext(), 12));
        mTextStyle = typedArray.getInt(R.styleable.TextFloatingActionButton_android_textStyle, 0);

        typedArray.recycle();

        mTextDrawable = new TextDrawable(getContext());
        mTextDrawable.setText(mText);
        mTextDrawable.setTextAlign(Layout.Alignment.ALIGN_CENTER);
        mTextDrawable.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
        mTextDrawable.setTextStyle(mTextStyle);
        mTextDrawable.setTextColor(mTextColor);
        setImageDrawable(mTextDrawable);
    }

    public void setText(String text) {
        mText = text;
        mTextDrawable.setText(mText);
    }

    public void setTextColor(int textColor) {
        mTextColor = textColor;
        mTextDrawable.setTextColor(mTextColor);
    }

    public void setTextSize(int textSize) {
        mTextSize = textSize;
        mTextDrawable.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
    }

    public void setTextStyle(int textStyle) {
        mTextStyle = textStyle;
        mTextDrawable.setTextStyle(mTextStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
